package actions.generate.dialog;

import utils.ClipBoardUtil;
import utils.CommonUtil;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class BindViewPreviewDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextArea bindViewPreview;

    public static void show(String defaultString) {
        BindViewPreviewDialog dialog = new BindViewPreviewDialog();
        dialog.bindViewPreview.setText(defaultString);
        CommonUtil.showDialog(dialog, "生成预览，点击确定复制到粘贴板");
    }

    private BindViewPreviewDialog() {
        setContentPane(contentPane);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        ClipBoardUtil.setSysClipboardText(bindViewPreview.getText());
        dispose();
    }

    private void onCancel() {
        dispose();
    }

    public static void main(String[] args) {
        BindViewPreviewDialog.show("@BindView(R.id.mainTv1)\n" +
                "TextView mainTv1;\n @BindView(R.id.mainTv2)\n" +
                "TextView mainTv2;\n @BindView(R.id.linearContainer)\n" +
                " LinearLayout linearContainer;\n " +
                "@BindView(R.id.lineTv1) \nTextView lineTv1;\n");
    }
}
